package com.wswy.wzcx.ui.coupon

import android.app.Activity
import android.arch.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.che.libcommon.ui.VOMessage
import com.che.libcommon.ui.loading.ILoadingView
import com.wswy.wzcx.R
import com.wswy.wzcx.model.home.RouterUtils
import com.wswy.wzcx.module.base.CBaseLoadingFragment
import com.wswy.wzcx.ui.Constants
import kotlinx.android.synthetic.main.fragment_coupon_choose.*

class ChooseCouponFragment : CBaseLoadingFragment() {


    override fun getLoadingFrameId(): Int {
        return R.id.fl_content
    }

    companion object {

       const val TAG = "ChooseCoupon"

        @JvmStatic
        fun newInstance(bundle: Bundle?):ChooseCouponFragment{

            return ChooseCouponFragment().apply {
                arguments = bundle
            }
        }

    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_coupon_choose,container,false)
    }

    override fun getConfigure(): ILoadingView.LoadingConfigure =object : ILoadingView.SampleLoadingConfigure() {
        override fun getOnRetryClickListener(): View.OnClickListener {
            return View.OnClickListener {
                showLoading(true)
                couponViewModel.load()
            }
        }
    }

    override fun getFragmentTitle(): String {
        return "选择优惠券"
    }

    private lateinit var couponViewModel: CouponViewModel
    private lateinit var adapter: CouponListAdapter

    private var hasCouponList = false
    private var goActFlag = false

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        couponViewModel = provideViewModel(CouponViewModel::class.java)


        recycler_view.layoutManager = LinearLayoutManager(context)


        adapter = CouponListAdapter(true)

        recycler_view.adapter = adapter

        couponViewModel.getCouponRespLiveData().observe(this, Observer {

            it?.run {

                if (isOk()){

                    showData()

                    //有优惠活动
                    data?.activityModel?.image?.let {
                        img_top_banner.visibility = View.VISIBLE
                        img_top_banner.setImageURI(it)
                    }?:kotlin.run {
                        img_top_banner.visibility = View.GONE
                    }

                    if (couponViewModel.selectedId == -1L){
                        couponViewModel.selectedId = arguments?.getLong(Constants.EXTRA_DATA_ID,-1)?:-1
                    }

                    if (couponViewModel.selectedId > 0){
                        val pos  = data?.list?.indexOfFirst {
                            couponViewModel.selectedId == it.id
                        }?:-1

                        if (pos != -1){
                            adapter.setDefaultSelectedPosition(pos)
                        }
                    }


                    if (data?.list.isNullOrEmpty()){
                        //没有优惠卷
                        hasCouponList = false

                        recycler_view.visibility = View.GONE

                        tv_no_coupon.visibility = View.VISIBLE

                        if (!TextUtils.isEmpty(data?.activityModel?.name)){
                            //有优惠活动
                            btn_ok.visibility = View.VISIBLE
                            btn_ok.text = data?.activityModel?.name
                        }else{

                            //都没有
                            btn_ok.visibility = View.GONE
                        }

                    }else{

                        hasCouponList = true

                        btn_ok.visibility = View.VISIBLE

                        tv_no_coupon.visibility = View.GONE

                        btn_ok.text = "确认选择"

                        recycler_view.visibility = View.VISIBLE
                        adapter.setNewData(data?.list)
                        adapter.notifyDataSetChanged()
                    }

                }else if (inLoading()){
                    showLoading(true)
                }else if (hasError()){
                    showError(VOMessage.create(null))
                }
            }

        })

        img_top_banner.setOnClickListener {

            gotoActivity()

        }

        btn_ok.setOnClickListener {
            //完成

            if (hasCouponList) {

                activity?.run {

                    setResult(Activity.RESULT_OK, Intent().apply {
                        putExtra(Constants.EXTRA_DATA, adapter.getSelectedData())
                    })
                    finish()
                }
            }else{

                //去活动

                gotoActivity()
            }
        }

        couponViewModel.load()
    }

    private fun gotoActivity(){
        couponViewModel.getCouponRespLiveData().value?.data?.activityModel?.url?.run {

            RouterUtils.getWebIntent(context,this).apply {
                putExtra("addToken",true)
            }.let {
                startActivity(it)
            }
            goActFlag = true
        }
    }

    override fun onStart() {
        super.onStart()
        if (goActFlag){

            goActFlag = false

            if (this::couponViewModel.isInitialized){

                if (this::adapter.isInitialized){
                    adapter.getSelectedData()?.run {
                        couponViewModel.selectedId = id
                    }
                }

                couponViewModel.load()
            }
        }

    }

}
